package cn.jdy.framework.util;

import java.io.IOException;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JsonUtil工具类，使用jackson替代之前的Gson工具类
 * @author zhaigt
 * @date 2015年3月7日
 */
public class JsonUtil {
  
  /**
   * 将对象转为json
   * @param obj
   * @return
   */
  public static String toJson(Object obj) {
    try {
      return new ObjectMapper().writeValueAsString(obj);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
  
  /**
   * 将对象转为json
   * @param obj
   * @param fmt "yyyy-MM-dd HH:mm:ss"
   * @return
   */
  public static String toJson(Object obj,String fmt) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      
      //设置日期格式  
      SimpleDateFormat sfmt = new SimpleDateFormat(fmt);  
      mapper.setDateFormat(sfmt);
      
      return mapper.writeValueAsString(obj);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
  
 

  /**
   * 将json串转为对象
   * @param str
   * @param valueType
   * @return
   */
  public static <T> T toObj(String str,Class<T> valueType){
    try {
      return new ObjectMapper().readValue(str, valueType);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

}
